package UI.List
{
	import Events.UIListEvent;
	
	import flash.display.*;
	import flash.events.*;
	
	import mx.controls.*;
	import mx.core.UIComponent;
	
	public class UIList extends UIComponent
	{
		private const BACKGROUND_COLOR:uint=uint(0xE6E6E6);
		private const STROKE_COLOR:uint = uint(0x000000);
		private const STROKE_SIZE:int = 5;
		private const ITEM_HEIGHT:Number = 20;
		
		private var strokeBackground:Bitmap;
		private var listBackground:Bitmap;
		
		private var items:Vector.<UIListItem>;
		
		public function UIList(width:Number=100)
		{
			items=new Vector.<UIListItem>();
			strokeBackground = new Bitmap(new BitmapData(width,1,false,STROKE_COLOR));
			listBackground = new Bitmap(new BitmapData(width-STROKE_SIZE*2,1,false,BACKGROUND_COLOR));
			
			addChildren();
			positionElements();
		}
		
		public function addItem(item:UIListItem):void
		{
			items.push(item);
			item.addEventListener(MouseEvent.CLICK, selectItem);
			item.buttonMode=true;
			item.height = ITEM_HEIGHT;
			item.width = listBackground.width;
			addChild(item);
			positionElements();
		}
		
		private function selectItem(e:MouseEvent):void
		{
			for each(var item:UIListItem in items)
			{
				if(e.target==item)
					item.hilight=true;
				else
					item.hilight=false;
			}
			dispatchEvent(new UIListEvent(UIListEvent.SELECT,e.target.itemName));
		}
		
		public function removeSelectedItem():void
		{
			for(var i:int=0;i<items.length;i++)
			{
				if(items[i].hilighted)
				{
					removeChild(items[i]);
					items.splice(i,1);
					positionElements();
					return;
				}
			}
		}
		
		public function removeLastItem():void
		{
			removeChild(items.pop());
			positionElements();
		}
		
		private function addChildren():void
		{
			addChild(strokeBackground);
			addChild(listBackground);
		}
		
		private function positionElements():void
		{
			listBackground.height = items.length*ITEM_HEIGHT;
			strokeBackground.height = listBackground.height+STROKE_SIZE*2;
			
			listBackground.x=STROKE_SIZE;
			listBackground.y=STROKE_SIZE;
			for(var i:int=0;i<items.length;i++)
			{
				items[i].x=STROKE_SIZE;
				items[i].y=(i*ITEM_HEIGHT)+STROKE_SIZE;
			}
		}
		
		public function get selection():String
		{
			for each(var item:UIListItem in items)
			{
				if(item.hilighted)
					return item.itemName;
			}
			return null;
		}
		
		public override function get width():Number
		{
			return strokeBackground.width;
		}
		
		public override function set width(w:Number):void
		{
			strokeBackground.width=w;
			listBackground.width=w-STROKE_SIZE*2;
			for each(var item:UIListItem in items)
			{
				item.width = listBackground.width;
			}
		}
		
		public override function get height():Number
		{
			return strokeBackground.height;
		}
	}
}